package com.indexingsystem.system.controller;


import com.indexingsystem.boss.Vo.*;
import com.indexingsystem.boss.common.PagedResult;
import com.indexingsystem.boss.common.ProgramLogsCommon;
import com.indexingsystem.boss.entity.ExportThemeWordsListResVo;
import com.indexingsystem.boss.entity.IdxSynonym;
import com.indexingsystem.boss.entity.IdxThemeWords;
import com.indexingsystem.boss.entity.ProgramLogs;
import com.indexingsystem.boss.logback.LogCvt;
import com.indexingsystem.boss.utils.DateUtil;
import com.indexingsystem.system.service.IProgramLogsService;
import com.indexingsystem.system.service.IdxExportThemeWordsService;
import com.indexingsystem.system.service.IdxSynonymService;
import com.indexingsystem.system.service.IdxThemeWordsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/IndexingSystem/Service")
public class IdxThemeWordController {

    private ProgramLogs logs;

    @Resource
    private IProgramLogsService logsService;

    @Resource
    private IdxExportThemeWordsService idxExportThemeWordsService;
    @Resource
    private IdxThemeWordsService idxThemeWordsService;
    @Resource
    private IdxSynonymService idxSynonymService;


    /**
     * @Discription 3.9 批量启用禁用同义词。
     * @Author mineary
     * @Date 10:00 2018/10/26
     * @Param [reqVo]
     * @Return java.util.Map<java.lang.String,java.lang.Object>
     */
    @RequestMapping(value = "/Synonym/updateSynonymStatus", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateSynonymStatus(@RequestBody UpdateSynonymStatusReqVo reqVo) {
        LogCvt.info("/Service/Synonym/updateSynonymStatus");
        Map<String, Object> result = new HashMap<>();
        List<IdxSynonym> list = new ArrayList<>();
        String message = "操作失败";
        String result_code = "9999";
        if (null != reqVo && reqVo.isNotBlank()) {
            LogCvt.info(reqVo.toString());
            List<String> ID = reqVo.getIds();
            try {

                Integer count = idxSynonymService.selectCountByIds(ID);
                if (reqVo.getStatus() != 0 && reqVo.getStatus() != -1) {
                    message = "状态参数无效！";
                } else if(idxSynonymService.selectCountByIds(reqVo.getIds()) < reqVo.getIds().size()) {
                    message = "存在错误的ID参数！";
                } else {
                    for (String id : ID) {
                        IdxSynonym synonym = new IdxSynonym();
                        synonym.setStatus(reqVo.getStatus());
                        synonym.setSynonymId(id);
                        list.add(synonym);
                    }
                    Integer i = idxSynonymService.updateSynonymStatusByIdBatch(list);
                    LogCvt.info("更新idx_synonym:" + i);
                    message = "操作成功！";
                    result_code = "0000";
                }
            } catch (Exception ex) {
                LogCvt.error("批量启用禁用同义词失败，原因：" + ex.getMessage());
                logs = ProgramLogsCommon.init();
                logs.setMessage("/Service/Synonym/updateSynonymStatus");
                logs.setLevel("1");
                logs.setLogger("ToDataBase");
                logs.setLogTime(DateUtil.parseFormatToDate(DateUtil.getCurTotalDate()));
                logs.setException(ex.toString());
                logsService.insertSelective(logs);

                message = "操作失败：" + ex.getMessage();
            }
        } else {
            message = "参数不全！";
            result_code = "6666";
        }

        result.put("message", message);
        result.put("result_code", result_code);
        LogCvt.info(result.toString());
        return result;
    }

    /**
     * @Discription 4.19 导出主题词
     * @Author mineary
     * @Date 20:37 2018/10/25
     * @Param [reqVo]
     * @Return java.util.Map<java.lang.String       ,       java.lang.Object>
     */
    @RequestMapping(value = "/ThemeWords/ExportThemeWords", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> ExportThemeWords(@RequestBody ExportTableWordsReqVo reqVo) {
        LogCvt.info("/Service/ThemeWords/ExportThemeWords");
        Map<String, Object> result = new HashMap<>();
        String message = "操作失败";
        String result_code = "9999";
        if (null != reqVo) {
            System.out.println(reqVo.toString());
            try {
                if (!StringUtils.isNotBlank(reqVo.getExportPath())) {
                    message = "导出路径不能为空！";
                } else if (!StringUtils.isNotBlank(reqVo.getExportType())) {
                    message = "导出类型不能为空！";
                } else {
                    //idxThemeTableService.export(reqVo, );
                    String s = idxThemeWordsService.exportThemeWords(reqVo);
                    if (s == null) {
                        message = "操作成功！";
                        result_code = "0000";
                    } else {
                        message = s;
                    }
                }

            } catch (Exception ex) {
                String reason = "";
                if (ex instanceof IOException) {
                    reason = "导出文件写入到磁盘异常！";
                } else {
                    reason = ex.getMessage();
                }
                LogCvt.error("产品标引结果导出失败，原因：" + reason);
                logs = ProgramLogsCommon.init();
                logs.setMessage("/Service/ThemeWords/ExportThemeWords");
                logs.setLevel("1");
                logs.setLogger("ToDataBase");
                logs.setLogTime(DateUtil.parseFormatToDate(DateUtil.getCurTotalDate()));
                logs.setException(ex.toString());
                logsService.insertSelective(logs);

                message = "操作失败：" + reason;
            }
        } else {
            message = "参数不全！";
            result_code = "6666";
        }
        result.put("message", message);
        result.put("result_code", result_code);
        LogCvt.info(result.toString());
        return result;
    }

    /**
     * 4.20 批量删除主题词导出历史记录
     *
     * @param reqVo
     * @return
     */
    @RequestMapping(value = "/ThemeWords/delExportThemeWords", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> delExportThemeWords(@RequestBody(required = false) DelExportThemeWordsReqVo reqVo) {
        LogCvt.info("/Service/ThemeWords/delExportThemeWords");
        LogCvt.info(reqVo.toString());
        Map<String, Object> result = new HashMap<>();
        String message = "操作失败！";
        String result_code = "9999";
        if (null != reqVo) {
            try {
                if (reqVo.getIds() == null || reqVo.getIds().size() < 1) {
                    message = "删除ID参数为空！";
                } else if (idxExportThemeWordsService.selectCountByIds(reqVo.getIds()) < reqVo.getIds().size()) {
                    message = "存在错误的ID参数！";
                } else {
                    idxExportThemeWordsService.deleteThemeWordsExport(reqVo);
                    message = "操作成功！";
                    result_code = "0000";
                }
            } catch (Exception ex) {
                LogCvt.error("批量删除主题词导出历史记录失败，原因：" + ex.getMessage());
                logs = ProgramLogsCommon.init();
                logs.setMessage("/Service/ThemeWords/delExportThemeWords");
                logs.setLevel("1");
                logs.setLogger("ToDataBase");
                logs.setLogTime(DateUtil.parseFormatToDate(DateUtil.getCurTotalDate()));
                logs.setException(ex.toString());
                logsService.insertSelective(logs);

                message = "操作失败：" + ex.getMessage();
            }
        }
        result.put("message", message);
        result.put("result_code", result_code);
        LogCvt.info(result.toString());
        return result;
    }


    /**
     * 4.21 查询主题词导出历史记录
     * 如果发生报错，可能是因为数据表中缺少export_type字段。
     * @param reqVo
     * @return
     */
    @RequestMapping(value = "/ThemeWords/getExportThemeWordsList", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getExportThemeWordsList(@RequestBody(required = false) ExportThemeWordsListReqVo reqVo) {
        LogCvt.info("/Service/ThemeWords/getExportThemeWordsList");
        Map<String, Object> result = new HashMap<>();
        String message = "操作失败！";
        String result_code = "9999";
        if (null != reqVo) {
            System.out.println(reqVo.toString());
            try {

                PagedResult<ExportThemeWordsListResVo> pagedResult = idxExportThemeWordsService.getExportThemeWordsList(reqVo);
                List<ExportThemeWordsListResVo> data = pagedResult.getDataList();
                result.put("length", pagedResult.getTotal());
                result.put("data", data);
                message = "操作成功！";
                result_code = "0000";
            } catch (Exception ex) {
                if (ex instanceof ParseException) {
                    message = "日期格式有误！";
                } else {
                    message = ex.getMessage();
                }
                LogCvt.error("导出主题词列表查询失败，原因：" + ex.getMessage());
                logs = ProgramLogsCommon.init();
                logs.setMessage("/Service/ThemeWords/getExportThemeWordsList");
                logs.setLevel("1");
                logs.setLogger("ToDataBase");
                logs.setLogTime(DateUtil.parseFormatToDate(DateUtil.getCurTotalDate()));
                logs.setException(ex.toString());
                logsService.insertSelective(logs);

                message = "操作失败：" + message;
            }
        }
        result.put("message", message);
        result.put("result_code", result_code);
        LogCvt.info(result.toString());
        return result;
    }

    /**
     * 4.26 批量修改主题词的启用禁用状态。
     *
     * @param reqVo
     * @return
     */
    @RequestMapping(value = "/ThemeWords/updateThemeWordsStatus", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateThemeWordsStatus(@RequestBody AuditThemeWordStatusReqVo reqVo) {
        LogCvt.info("/Service/ThemeWords/updateThemeWordsStatus");
        Map<String, Object> result = new HashMap<>();
        List<IdxThemeWords> list = new ArrayList<>();
        LogCvt.info(reqVo.toString());
        String message = "操作失败";
        String result_code = "9999";
        if (null != reqVo && reqVo.isNotBlank()) {
            try {
                LogCvt.info(reqVo.toString());
                Integer count = idxThemeWordsService.selectCountByIds(reqVo.getIds());
                if (count < reqVo.getIds().size()) {
                    message = "存在错误的ID参数！";
                } else if (reqVo.getStatus() != 0 && reqVo.getStatus() != -1) {
                    message = "状态参数无效！";
                } else {
                    for (String id : reqVo.getIds()) {
                        IdxThemeWords itw = new IdxThemeWords();
                        itw.setStatus(reqVo.getStatus());
                        itw.setThemeWordsId(Integer.valueOf(id));
                        list.add(itw);
                    }
                    Integer i = idxThemeWordsService.updateThemeWordsStatusByIdBatch(list);
                    LogCvt.info("idx_task:" + i);
                    message = "操作成功！";
                    result_code = "0000";
                }
            } catch (Exception ex) {
                LogCvt.error("批量更新主题词状态失败，原因：" + ex.getMessage());
                logs = ProgramLogsCommon.init();
                logs.setMessage("/Service/ThemeWords/updateThemeWordsStatus");
                logs.setLevel("1");
                logs.setLogger("ToDataBase");
                logs.setLogTime(DateUtil.parseFormatToDate(DateUtil.getCurTotalDate()));
                logs.setException(ex.toString());
                logsService.insertSelective(logs);

                message = "操作失败：" + ex.getMessage();
            }
        } else {
            message = "参数不全！";
            result_code = "6666";
        }

        result.put("message", message);
        result.put("result_code", result_code);
        LogCvt.info(result.toString());
        return result;
    }
}
